<?php
// 应用公共文件


use think\facade\Cache;
use Qiniu\Auth;

const version = 7; //css与js版本号

const jquery = 'https://libs.baidu.com/jquery/2.1.4/jquery.min.js';
const bootstrap_min_css = 'http://res.itsub.cn/lib/bootstrap/3.4.1/css/bootstrap.min.css';
const bootstrap_min_js = 'http://res.itsub.cn/lib/bootstrap/3.4.1/js/bootstrap.min.js';

const keywords = "代码,代码分享,代码例子,毕业设计,课程设计,源码,java代码,酷代码,最代码,好例子,程序";


//腾讯云授权
function qq_vod_sign($url)
{
    $p1 = strpos($url,'/',9);
    $p2 = strrpos($url,'/');
    $dir = substr($url,$p1,$p2-$p1+1);

    $key = 'XK1RrVSvlC2jsETbBeMv';
    $t = dechex(time()+3600);   //过期时间戳
    $exper = '';   //试看时长（例如'300'代表5分钟）
    $rlimit = '';
    $us = '';
    $text = $key . $dir . $t . $exper . $rlimit . $us;
    $sign = md5($text);
    $url = $url . '?t=' . $t . '&exper=' . $exper . '&us=' . $us . '&sign=' . $sign;
    return $url;
}
//七牛云授权
function qn_sign($url)
{
    $accessKey ="A4m-_ysJ4BSkovlpd6OVZZ3HGwgZ-Mb0zorW0Z5q";
    $secretKey = "2RFgCjEYXzMla5NyPN3_5nBHaZuAu1xP2LsL_8jw";
    // 构建Auth对象
    $auth = new Auth($accessKey, $secretKey);
    // 私有空间中的外链 http://<domain>/<file_key>
    $baseUrl = $url.'?pm3u8/0/43200'; //授权12小时
    // 对链接进行签名
    $signedUrl = $auth->privateDownloadUrl($baseUrl);
    return $signedUrl;
}


/**
 *+----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 *+----------------------------------------------------------
 * @static
 * @access public
 *+----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 *+----------------------------------------------------------
 * @return string
 *+----------------------------------------------------------
 */

function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
        if($suffix){
            if(strlen($str)>$length)
                return mb_substr($str, $start, $length, $charset)."...";
            else
                return mb_substr($str, $start, $length, $charset);
        }else{
            return mb_substr($str, $start, $length, $charset);
        }
    }elseif(function_exists('iconv_substr')) {
        if($suffix){
            return iconv_substr($str,$start,$length,$charset);
        }else{
            return iconv_substr($str,$start,$length,$charset);
        }
    }
}

/**
 * 去除字符串中的不可见字符
 * @param $str
 * @return array|string|string[]
 */
function lcTrim($str)
{
    $search = array(" ","　","\n","\r","\t");
    $replace = array("","","","","");
    return str_replace($search, $replace, $str);
}

function datestr($str, $gs)
{
    return date($gs,strtotime($str));
}

/**
 * 计算文件大小
 * @param $filesize
 * @return string
 */
function fsize($size) {
    if($size >= 1073741824) {
        $ret = round($size / 1073741824 * 100) / 100 . ' GB';

    } elseif($size >= 1048576) {
        $ret = round($size / 1048576 * 100) / 100 . ' MB';

    } elseif($size >= 1024) {
        $ret = round($size / 1024 * 100) / 100 . ' KB';

    } else {
        $ret = $size . ' 字节';

    }

    return $ret;

}

function startWith($str,$pattern) {
    if(strpos($str,$pattern) === 0)
        return true;
    else
        return false;
}

function uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}

/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function http_post($url, $data) {

    $postdata = http_build_query($data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}


//从session获取缓存的用户信息，未登录则返回null
function loginUser()
{
    $user = session('login_user');
    if ($user == null) {
        return null;
    }
    return $user;
}
//刷新session中的用户信息，未登录则返回null
function loginUserReload()
{
    $user = session('login_user');
    if ($user == null) {
        return null;
    }
    $userModel = new \app\model\User();
    $user = $userModel->where('id', $user->id)->find();
    session('login_user', $user);
    return $user;
}

function json($arr)
{
    return json_encode($arr,JSON_UNESCAPED_UNICODE);
}


function cc_ftp_file_upload($remote_filename, $local_filename)
{
    $conn = null;
    try {
        $conn = ftp_connect("49.232.143.254");
        ftp_login($conn, "icode", "yWMsEJY6WkafH22n");
        ftp_pasv($conn, true);
        ftp_put($conn, $remote_filename, $local_filename, FTP_BINARY);
    } finally {
        ftp_close($conn);
    }

}

function cc_ftp_conn()
{
    $conn = null;
    $conn = ftp_connect("49.232.143.254");
    ftp_login($conn, "img", "nSyEBfmcX3H6ZzrZ");
    ftp_pasv($conn, true);
    return $conn;
}


include 'utils/Smtp.php';

function SendMail($receiver,$title,$content)
{
    $host = 'smtp.sina.com';
    $username = 'itsub@sina.com';
    $password = '1e9a321691a2d84e';
    $mail = new \gclinux\Smtper();
    //$mail->setDebug(true); //do you want to output the debug information.是否输出调试信息
    $mail->setServer($host, $username, $password, 465, true); //Seeting the SMTP server with SSL .SSL的SMTP服务器设置
    $mail->setFrom($username); //Email Sender name 发送者
    $mail->setReceiver($receiver); //Email reciver 接收者
    //$mail->setCc("XXXX"); //Set CC .抄送
    //$mail->setBcc("XXXXX"); //Set CC,multiple calls will append.多次调用会添加.
    //$mail->addAttachment("XXXX.png"); //Attachment 附件
    $mail->setMail($title, $content); //the titile and body 标题和内容
    return $mail->send();
}

function check_email($email)
{
    $result = trim($email);
    if (filter_var($result, FILTER_VALIDATE_EMAIL))
    {
        return true;
    }
    else
    {
        return false;
    }
}


// 说明：获取完整URL

function get_app_site()
{
    $pageURL = 'http';

    if (@$_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    $host = @$_SERVER["HTTP_HOST"];
    $port = @$_SERVER["SERVER_PORT"];
    $pageURL .= $host;
    return $pageURL;
}

function dict($name,$key){
    $rs = \think\facade\Db::query('select * from sys_dict_item a left join sys_dict b on a.dict_id=b.id where b.name=:name and a.name=:key',
        ['name'=>$name,'key'=>$key]);
    return $rs[0]['value'];
}

define("BASE_URL", get_app_site());
